package service;

import entity.User;
import entity.Xinwen;
import util.DataSourceUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class XinwenService {

    public static void addXinwen(int id,String newName,String newlink) {
        String sql = "INSERT INTO xinwen VALUES(?,?,?)";
        try(Connection conn = DataSourceUtils.getConnection();
            PreparedStatement st = conn.prepareStatement(sql)) {
            st.setInt(1, id);
            st.setString(2, newlink);
            st.setString(3, newName);
            st.executeUpdate();
        }catch (SQLException e) {
            System.out.println("插入异常");
        }
    }
    public static void deleXinwen(int id) {
        String sql = "delete from xinwen where id= ?";
        try(Connection conn = DataSourceUtils.getConnection();
            PreparedStatement st = conn.prepareStatement(sql)) {
            st.setInt(1, id);
            st.executeUpdate();
        }catch (SQLException e) {
            System.out.println("删除异常");
        }
    }

    public static List<Xinwen> listUsers() {
        List<Xinwen> xinwens = new ArrayList<>();
        String sql = "SELECT * FROM xinwen";
        try(Connection conn = DataSourceUtils.getConnection();
            PreparedStatement st = conn.prepareStatement(sql);
            ResultSet rs = st.executeQuery()) {
            while (rs.next()) {
                Xinwen xinwen = new Xinwen(rs.getInt("id"),rs.getString("name"), rs.getString("link"));
                xinwens.add(xinwen);
            }
        } catch (SQLException e) {
            System.out.println("List异常");
        }
        return xinwens;
    }

    public static Xinwen getX(int id) {
        Xinwen xinwen = null;
        String sql = "SELECT * FROM users WHERE id=?";
        try(Connection conn = DataSourceUtils.getConnection();
            PreparedStatement st = conn.prepareStatement(sql)) {
            st.setInt(1, id);
            try(ResultSet rs = st.executeQuery()) {
                while (rs.next()) {
                   xinwen = new Xinwen(rs.getInt("id"), rs.getString("name"), rs.getString("link"));
                }
            }
        } catch (SQLException e) {
            System.out.println("获取异常");
        }
        return xinwen;
    }
}
